<template>
  <div class="page-container">
    <el-card>
      <!-- 添加按钮 -->
      <template #header>
        <el-button type="primary" :icon="Plus" @click="onShowDialog">添加</el-button>
      </template>
      <!-- 表格 -->
      <el-table :data="state.trademarkList" style="width: 100%" border stripe>
        <el-table-column type="index" label="序号" width="100" />
        <el-table-column prop="tmName" label="品牌名称" />
        <el-table-column prop="name" label="品牌Logo">
          <template #default="{ row }">
            <img class="logoUrl" :src="row.logoUrl" alt="" />
          </template>
        </el-table-column>

        <el-table-column prop="address" label="操作">
          <template #default="{ row }">
            <el-button type="warning" size="small" :icon="Edit" @click="editTrademark(row.id)"
              >修改</el-button
            >
            <el-button type="danger" size="small" :icon="Delete" @click="delTrademark(row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <!-- current-page：当前是第几页 -->
      <!-- page-size：每页展示多少条数据 -->
      <!-- layout：配置分页展示结构 -->
      <!-- total：总共有多少条数据 -->
      <el-pagination
        :current-page="state.page"
        :page-size="state.limit"
        :page-sizes="[10, 15, 20, 25]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="state.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <!-- el-dialog 弹框组件 -->
    <!-- v-model 控制弹框的展示与隐藏 -->
    <el-dialog
      v-model="showDialog"
      :title="isEdit ? '编辑品牌' : '添加品牌'"
      width="50%"
      align-center
      :before-close="handleClose"
    >
      <el-form :model="formData" label-width="90px" ref="formRef" :rules="rules">
        <el-form-item label="品牌名称" prop="tmName">
          <el-input v-model="formData.tmName" />
        </el-form-item>
        <el-form-item label="品牌Logo" prop="logoUrl">
          <!-- upload 上传组件 -->
          <!-- action 上传地址 -->
          <!-- show-file-list 是否显示已上传文件列表 -->
          <!-- on-success 图片上传成功以后的逻辑 -->
          <!-- before-upload 上传之前 -->
          <el-upload
            class="avatar-uploader"
            :action="uploadUrl"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="formData.logoUrl" :src="formData.logoUrl" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancelHandler">取消</el-button>
          <el-button type="primary" @click="confirmHandler">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { reactive, onMounted, ref } from 'vue'
import { Plus, Edit, Delete } from '@element-plus/icons-vue'
import {
  reqTrademarkInfo,
  reqTrademarkList,
  reqAddTrademark,
  reqUpdateTrademark,
  reqDelTrademark
} from '@/api/Trademark'
import type { IReqListRecord, ITrademarkState } from '@/types/trademark'
import type { FormInstance, UploadProps } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'

// 拼接上传的地址
const uploadUrl = import.meta.env.VITE_API_URL + '/admin/product/upload'

// 表单引用对象
const formRef = ref<FormInstance>()

// 是否是新增(false)或编辑(true)
const isEdit = ref(false)

// 控制弹框的隐藏与展示
const showDialog = ref(false)

// 新增和编辑功能需要收集的数据
const formData = ref({
  tmName: '', // 品牌 名字
  logoUrl: '' // 品牌 Logo
})

// 定义新增和编辑的验证规则
const rules = reactive({
  tmName: [{ required: true, message: '请输入品牌名称', trigger: 'blur' }],
  // 上传不是表单元素，所以 blur 和 change
  // 写规则的作用：是用来做兜底验证
  // 选择图片以后进行验证，需要使用方法
  logoUrl: [{ required: true, message: '请上传图片', trigger: 'change' }]
})

// 上传成功的回调
const handleAvatarSuccess: UploadProps['onSuccess'] = (response, uploadFile) => {
  // formData.value.logoUrl = URL.createObjectURL(uploadFile.raw!)
  formData.value.logoUrl = response.data
  // 如果验证通过，会将错误提示清除，如果验证没有通过，错误提示依然存在
  formRef.value?.validateField('logoUrl')
}

// 上传之前的逻辑
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.type !== 'image/jpeg') {
    ElMessage.error('图片格式必须是 jpeg 格式!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('上传的图片体积不能大于 2MB!')
    return false
  }
  return true
}

// 新增品牌按钮
const onShowDialog = () => {
  // false 是新增
  isEdit.value = false
  showDialog.value = true
}

// 点击编辑的按钮
const editTrademark = async (id: number) => {
  // true 是编辑
  isEdit.value = true
  showDialog.value = true

  // 调用接口，获取编辑这一项的数据
  const res = await reqTrademarkInfo(id)
  if (res.code === 200) {
    formData.value = res.data
  }
}

// 新增和编辑弹框确定按钮
const confirmHandler = async () => {
  // 进行兜底验证
  await formRef.value?.validate()

  const res = isEdit.value
    ? await reqUpdateTrademark(formData.value)
    : await reqAddTrademark(formData.value)

  if (res.code === 200) {
    // 给用户提示
    ElMessage.success(isEdit.value ? '修改品牌成功' : '新增品牌成功')
    // 关掉弹框、清除用户输入的信息
    cancelHandler()
    // 重新获取数据
    getTrademarkList()
  }
}

// 新增和编辑弹框取消按钮
const cancelHandler = () => {
  showDialog.value = false
  // 重置表单数据
  // formData.value.logoUrl = ''
  // formData.value.tmName = ''
  formRef.value?.resetFields()
}

// 新增和编辑弹框关闭之前
const handleClose = () => {
  cancelHandler()
}

// 删除品牌
const delTrademark = (row: IReqListRecord) => {
  ElMessageBox.confirm(`您确定要删除 ${row.tmName} 吗？`, '删除提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      const res = await reqDelTrademark(row.id)

      if (res.code === 200) {
        ElMessage({
          type: 'success',
          message: '删除成功'
        })

        getTrademarkList()
      }
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除'
      })
    })
}
//#region 列表渲染初始化
// 分页初始化数据
const state: ITrademarkState = reactive({
  page: 1, //当前页码
  limit: 10, //每页展示多少条
  total: 0, //数据总条数
  trademarkList: [] //品牌列表数据
})
// 获取品牌列表
const getTrademarkList = async () => {
  const res = await reqTrademarkList(state.page, state.limit)
  if (res.code === 200) {
    state.total = res.data.total
    state.trademarkList = res.data.records
  }
}
onMounted(() => {
  getTrademarkList()
})
// page-size改变时触发
const handleSizeChange = (value: number) => {
  state.limit = value
  getTrademarkList()
}
// current-page改变时触发
const handleCurrentChange = (value: number) => {
  state.page = value
  getTrademarkList()
}
//#endregion
</script>

<script lang="ts">
export default {
  name: 'TrademarkView'
}
</script>

<style lang="scss" scoped>
.container {
  margin-top: 20px;
}

.el-pagination {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.logoUrl {
  width: 100px;
  height: 60px;
}
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
